package com.jcodes.simple.module.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jcodes.simple.common.base.PageRo;
import com.jcodes.simple.module.auth.controller.ro.UserFindPageRo;
import com.jcodes.simple.module.auth.controller.ro.UserUpdateRo;
import com.jcodes.simple.module.auth.entity.User;
import jakarta.validation.Valid;
import org.springframework.core.convert.ConversionService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jcodes.simple.module.auth.controller.ro.UserCreateRo;
import com.jcodes.simple.module.auth.service.UserService;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Objects;

@RestController
@RequestMapping("/api/user")
public class UserController {

    private final UserService userService;
    private final ConversionService conversionService;

    public UserController(UserService userService, ConversionService conversionService) {
        this.userService = userService;
        this.conversionService = conversionService;
    }

    @PostMapping("create")
    public Long create(@RequestBody @Valid UserCreateRo ro) {
        User user = this.conversionService.convert(ro, User.class);
        this.userService.save(user);
        return user.getId();
    }

    @PostMapping("update")
    public Long update(@RequestBody UserUpdateRo ro) {
        User user = this.conversionService.convert(ro, User.class);
        this.userService.updateById(user);
        return user.getId();
    }

    @PostMapping("delete")
    public void delete(@RequestBody Long id) {
        this.userService.delete(id);
    }

    @GetMapping("findPage")
    public Page<User> findPage(@RequestBody PageRo<UserFindPageRo> pageRo) {
        UserFindPageRo query = pageRo.getQuery();
        Page<User> page = Page.of(pageRo.getCurrent(), pageRo.getSize());
        if (Objects.nonNull(pageRo.getOrders())) {
            page.setOrders(pageRo.getOrders());
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(query)) {
            queryWrapper.likeRight(User::getUsername, query.getUsername());
        }
        return this.userService.page(page, queryWrapper);
    }

}
